#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-5-23 下午2:47
# @Author  : Tom
# @Site    : 
# @File    : meiduo_signature.py
# @Software: PyCharm


from itsdangerous.jws import TimedJSONWebSignatureSerializer
from django.conf import settings


# 对json数据进行设置过期时间的加密和解密
def dumps(json_dict, expires):
    """加密: 将字典加密成字节，再解码"""
    serialter = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=expires)
    json_str = serialter.dumps(json_dict).decode()
    return json_str


def loads(json_str, expires):
    """解密：将字符串解密成字典，"""
    serialter = TimedJSONWebSignatureSerializer(secret_key=settings.SECRET_KEY, expires_in=expires)
    try:
        json_dict = serialter.loads(json_str)
    except:
        # 如果字符串过期回返回NONE
        return None
    else:
        return json_dict